"""
标题优化建议生成器
分析标题吸引力、生成优化建议和变体
"""

import re
from typing import Dict, List, Tuple, Optional, Any
from dataclasses import dataclass
from enum import Enum
import logging
from datetime import datetime

logger = logging.getLogger(__name__)


class TitleElementType(Enum):
    """标题元素类型"""
    NUMBER = "number"          # 数字
    QUESTION = "question"      # 疑问
    EMOTION = "emotion"        # 情感词
    URGENCY = "urgency"        # 紧迫感
    BENEFIT = "benefit"        # 利益点
    NEGATION = "negation"      # 否定词
    SUPERLATIVE = "superlative"  # 最高级
    BRAND = "brand"            # 品牌词


@dataclass
class TitleAnalysis:
    """标题分析结果"""
    original_title: str
    length: int
    char_count: int
    has_number: bool
    has_question: bool
    has_emotion: bool
    emotional_score: float
    readability_score: float
    keyword_coverage: float
    elements: List[TitleElementType]


@dataclass
class TitleVariant:
    """标题变体"""
    title: str
    style: str  # question, statement, list, how-to, etc.
    score: float
    improvements: List[str]
    keywords_used: List[str]


@dataclass
class TitleOptimizationResult:
    """标题优化结果"""
    analysis: TitleAnalysis
    attractiveness_score: float
    seo_score: float
    variants: List[TitleVariant]
    issues: List[str]
    suggestions: List[Dict[str, Any]]
    hot_keywords: List[str]


class TitleOptimizer:
    """标题优化器"""
    
    def __init__(self):
        """初始化优化器"""
        # 理想标题长度
        self.ideal_length_min = 10
        self.ideal_length_max = 30
        
        # 情感词库
        self.emotion_words = {
            'positive': ['惊人', '震撼', '绝佳', '完美', '卓越', '独家', '首选',
                        '最新', '必看', '热门', '精选', '顶级', '极致', '超值'],
            'negative': ['警惕', '避免', '危险', '错误', '陷阱', '失败', '问题'],
            'neutral': ['分析', '研究', '探讨', '解读', '理解', '认识', '了解']
        }
        
        # 紧迫感词汇
        self.urgency_words = [
            '立即', '马上', '现在', '今日', '限时', '速看', '紧急',
            '最后', '仅剩', '即将', '错过', '赶紧', '火速'
        ]
        
        # 利益点词汇
        self.benefit_words = [
            '提升', '改善', '增强', '优化', '节省', '赚取', '获得',
            '实现', '达成', '突破', '成功', '效率', '收益', '价值'
        ]
        
        # 疑问词
        self.question_words = [
            '如何', '怎么', '为什么', '什么', '哪些', '是否', '能否',
            '多少', '怎样', '何时', '谁', '哪里', '为何'
        ]
        
        # 数字模式
        self.number_patterns = [
            r'\d+', r'[一二三四五六七八九十百千万亿]+', 
            r'第[一二三四五六七八九十\d]+', r'TOP\s*\d+'
        ]
        
        # 标题模板
        self.title_templates = {
            'question': [
                "如何{action}{target}？",
                "为什么{subject}{verb}？",
                "{subject}的{number}个{method}"
            ],
            'list': [
                "{number}个{method}让你{benefit}",
                "{year}年{subject}的{number}大{trend}",
                "盘点：{subject}的{number}个{point}"
            ],
            'how_to': [
                "如何用{time}时间{action}",
                "从{start}到{end}：{subject}指南",
                "手把手教你{action}"
            ],
            'statement': [
                "{subject}：{description}",
                "深度解析{subject}的{aspect}",
                "{subject}{verb}的真相"
            ],
            'emotional': [
                "震撼！{subject}竟然{result}",
                "必看：{subject}的{secret}",
                "独家揭秘：{subject}背后的{story}"
            ]
        }
        
        # 热门关键词（示例）
        self.hot_keywords_db = [
            'AI', '人工智能', '大模型', 'ChatGPT', '数字化', '元宇宙',
            '新能源', '碳中和', '芯片', '5G', '区块链', '数据安全',
            '云计算', '物联网', '智能制造', '自动驾驶', '生物科技'
        ]
    
    def optimize(self, title: str, content: str = "", 
                keywords: List[str] = None) -> TitleOptimizationResult:
        """
        优化标题
        
        Args:
            title: 原始标题
            content: 文章内容（可选，用于提取关键词）
            keywords: 关键词列表（可选）
            
        Returns:
            标题优化结果
        """
        if not title or not title.strip():
            return self._empty_result("标题为空")
        
        # 分析原标题
        analysis = self._analyze_title(title, keywords)
        
        # 计算吸引力分数
        attractiveness_score = self._calculate_attractiveness(analysis)
        
        # 计算SEO分数
        seo_score = self._calculate_seo_score(analysis, keywords)
        
        # 检测问题
        issues = self._detect_issues(analysis)
        
        # 生成标题变体
        variants = self._generate_variants(title, content, keywords)
        
        # 生成优化建议
        suggestions = self._generate_suggestions(analysis, issues)
        
        # 获取热门关键词
        hot_keywords = self._get_hot_keywords(content)
        
        return TitleOptimizationResult(
            analysis=analysis,
            attractiveness_score=attractiveness_score,
            seo_score=seo_score,
            variants=variants,
            issues=issues,
            suggestions=suggestions,
            hot_keywords=hot_keywords
        )
    
    def _analyze_title(self, title: str, keywords: List[str] = None) -> TitleAnalysis:
        """分析标题"""
        # 基本指标
        length = len(title)
        char_count = len(re.findall(r'[\u4e00-\u9fff]', title)) + \
                    len(re.findall(r'\b[a-zA-Z]+\b', title))
        
        # 检测元素
        has_number = any(re.search(pattern, title) for pattern in self.number_patterns)
        has_question = any(word in title for word in self.question_words)
        has_emotion = self._has_emotion_word(title)
        
        # 计算情感分数
        emotional_score = self._calculate_emotional_score(title)
        
        # 计算可读性
        readability_score = self._calculate_readability_score(title)
        
        # 关键词覆盖率
        keyword_coverage = 0.0
        if keywords:
            covered = sum(1 for kw in keywords if kw in title)
            keyword_coverage = covered / len(keywords) if keywords else 0
        
        # 识别包含的元素
        elements = self._identify_elements(title)
        
        return TitleAnalysis(
            original_title=title,
            length=length,
            char_count=char_count,
            has_number=has_number,
            has_question=has_question,
            has_emotion=has_emotion,
            emotional_score=emotional_score,
            readability_score=readability_score,
            keyword_coverage=keyword_coverage,
            elements=elements
        )
    
    def _has_emotion_word(self, title: str) -> bool:
        """检查是否包含情感词"""
        all_emotion_words = []
        for words in self.emotion_words.values():
            all_emotion_words.extend(words)
        
        return any(word in title for word in all_emotion_words)
    
    def _calculate_emotional_score(self, title: str) -> float:
        """计算情感分数"""
        score = 0.0
        
        # 积极情感词
        for word in self.emotion_words['positive']:
            if word in title:
                score += 0.2
        
        # 消极情感词（适度使用）
        for word in self.emotion_words['negative']:
            if word in title:
                score += 0.1
        
        # 紧迫感
        for word in self.urgency_words:
            if word in title:
                score += 0.15
        
        # 利益点
        for word in self.benefit_words:
            if word in title:
                score += 0.15
        
        return min(1.0, score)
    
    def _calculate_readability_score(self, title: str) -> float:
        """计算可读性分数"""
        score = 1.0
        
        # 长度因素
        if self.ideal_length_min <= len(title) <= self.ideal_length_max:
            score *= 1.0
        else:
            score *= 0.7
        
        # 复杂词汇检测
        complex_chars = len(re.findall(r'[^\u4e00-\u9fff\w\s，。！？]', title))
        if complex_chars > 3:
            score *= 0.8
        
        # 标点符号使用
        punct_count = len(re.findall(r'[，。！？：；]', title))
        if punct_count > 2:
            score *= 0.9
        
        return score
    
    def _identify_elements(self, title: str) -> List[TitleElementType]:
        """识别标题元素"""
        elements = []
        
        # 数字
        if any(re.search(pattern, title) for pattern in self.number_patterns):
            elements.append(TitleElementType.NUMBER)
        
        # 疑问
        if any(word in title for word in self.question_words):
            elements.append(TitleElementType.QUESTION)
        
        # 情感
        if self._has_emotion_word(title):
            elements.append(TitleElementType.EMOTION)
        
        # 紧迫感
        if any(word in title for word in self.urgency_words):
            elements.append(TitleElementType.URGENCY)
        
        # 利益点
        if any(word in title for word in self.benefit_words):
            elements.append(TitleElementType.BENEFIT)
        
        # 否定词
        if any(word in title for word in ['不', '无', '没', '非', '勿']):
            elements.append(TitleElementType.NEGATION)
        
        # 最高级
        if any(word in title for word in ['最', '第一', 'TOP', '顶级', '极致']):
            elements.append(TitleElementType.SUPERLATIVE)
        
        return elements
    
    def _calculate_attractiveness(self, analysis: TitleAnalysis) -> float:
        """计算吸引力分数"""
        score = 0.0
        
        # 基础分（可读性）
        score += analysis.readability_score * 0.3
        
        # 情感因素
        score += analysis.emotional_score * 0.25
        
        # 元素多样性
        element_score = len(analysis.elements) * 0.1
        score += min(0.3, element_score)
        
        # 特定元素加分
        if analysis.has_number:
            score += 0.1
        if analysis.has_question:
            score += 0.05
        
        return min(1.0, score)
    
    def _calculate_seo_score(self, analysis: TitleAnalysis, 
                            keywords: List[str] = None) -> float:
        """计算SEO分数"""
        score = 0.0
        
        # 长度因素（SEO友好长度）
        if 15 <= analysis.length <= 60:
            score += 0.3
        elif 10 <= analysis.length <= 70:
            score += 0.2
        else:
            score += 0.1
        
        # 关键词覆盖
        if keywords:
            score += analysis.keyword_coverage * 0.4
        
        # 可读性
        score += analysis.readability_score * 0.2
        
        # 包含数字（有利于点击率）
        if analysis.has_number:
            score += 0.1
        
        return min(1.0, score)
    
    def _detect_issues(self, analysis: TitleAnalysis) -> List[str]:
        """检测标题问题"""
        issues = []
        
        # 长度问题
        if analysis.length < self.ideal_length_min:
            issues.append(f"标题过短（{analysis.length}字），建议{self.ideal_length_min}-{self.ideal_length_max}字")
        elif analysis.length > self.ideal_length_max * 1.5:
            issues.append(f"标题过长（{analysis.length}字），影响展示效果")
        
        # 吸引力不足
        if not analysis.elements:
            issues.append("标题缺少吸引力元素（数字、疑问、情感词等）")
        
        # 关键词覆盖不足
        if analysis.keyword_coverage < 0.3:
            issues.append("标题未包含足够的关键词，影响SEO效果")
        
        # 可读性问题
        if analysis.readability_score < 0.5:
            issues.append("标题可读性较差，可能包含生僻字或结构复杂")
        
        return issues
    
    def _generate_variants(self, original_title: str, content: str,
                          keywords: List[str] = None) -> List[TitleVariant]:
        """生成标题变体"""
        variants = []
        
        # 提取关键元素
        if not keywords and content:
            keywords = self._extract_keywords_from_content(content)
        
        # 疑问式变体
        question_variant = self._create_question_variant(original_title, keywords)
        if question_variant:
            variants.append(question_variant)
        
        # 数字列表式变体
        list_variant = self._create_list_variant(original_title, keywords)
        if list_variant:
            variants.append(list_variant)
        
        # How-to式变体
        howto_variant = self._create_howto_variant(original_title, keywords)
        if howto_variant:
            variants.append(howto_variant)
        
        # 情感式变体
        emotional_variant = self._create_emotional_variant(original_title, keywords)
        if emotional_variant:
            variants.append(emotional_variant)
        
        # 简洁陈述式变体
        statement_variant = self._create_statement_variant(original_title, keywords)
        if statement_variant:
            variants.append(statement_variant)
        
        return variants
    
    def _create_question_variant(self, original: str, 
                                keywords: List[str] = None) -> Optional[TitleVariant]:
        """创建疑问式变体"""
        if not keywords:
            keywords = []
        
        # 简单转换
        if '的' in original:
            parts = original.split('的')
            if len(parts) >= 2:
                title = f"如何{parts[1]}？{parts[0]}指南"
                return TitleVariant(
                    title=title[:30],  # 限制长度
                    style="question",
                    score=0.75,
                    improvements=["添加疑问词增加好奇心", "明确指南性质"],
                    keywords_used=keywords[:2] if keywords else []
                )
        
        return None
    
    def _create_list_variant(self, original: str, 
                            keywords: List[str] = None) -> Optional[TitleVariant]:
        """创建数字列表式变体"""
        if not keywords:
            keywords = []
        
        # 添加数字
        numbers = ['5个', '7个', '10个', '3步', '5步']
        import random
        number = random.choice(numbers)
        
        if keywords:
            title = f"{number}方法教你{keywords[0]}"
        else:
            title = f"{number}要点：{original}"
        
        return TitleVariant(
            title=title[:30],
            style="list",
            score=0.8,
            improvements=["添加具体数字", "列表式结构清晰"],
            keywords_used=keywords[:1] if keywords else []
        )
    
    def _create_howto_variant(self, original: str,
                             keywords: List[str] = None) -> Optional[TitleVariant]:
        """创建How-to式变体"""
        if not keywords:
            keywords = []
        
        if keywords:
            title = f"一文读懂{keywords[0]}：从入门到精通"
        else:
            title = f"手把手教你：{original}"
        
        return TitleVariant(
            title=title[:30],
            style="how-to",
            score=0.7,
            improvements=["教程式标题", "明确学习路径"],
            keywords_used=keywords[:1] if keywords else []
        )
    
    def _create_emotional_variant(self, original: str,
                                 keywords: List[str] = None) -> Optional[TitleVariant]:
        """创建情感式变体"""
        if not keywords:
            keywords = []
        
        emotion_prefixes = ['震撼！', '必看：', '独家：', '重磅！']
        import random
        prefix = random.choice(emotion_prefixes)
        
        title = f"{prefix}{original}"
        
        return TitleVariant(
            title=title[:30],
            style="emotional",
            score=0.65,
            improvements=["添加情感词汇", "增强点击欲望"],
            keywords_used=keywords[:2] if keywords else []
        )
    
    def _create_statement_variant(self, original: str,
                                 keywords: List[str] = None) -> Optional[TitleVariant]:
        """创建简洁陈述式变体"""
        if not keywords:
            keywords = []
        
        # 提取核心词
        if '的' in original:
            parts = original.split('的')
            if len(parts) >= 2:
                title = f"{parts[0]}：{parts[1]}"
            else:
                title = original
        else:
            title = original
        
        # 确保包含关键词
        if keywords and keywords[0] not in title:
            title = f"{keywords[0]}：{title}"
        
        return TitleVariant(
            title=title[:30],
            style="statement",
            score=0.7,
            improvements=["简洁明了", "重点突出"],
            keywords_used=keywords[:1] if keywords else []
        )
    
    def _extract_keywords_from_content(self, content: str) -> List[str]:
        """从内容中提取关键词（简化版）"""
        # 这里简化处理，实际应该使用更复杂的NLP方法
        words = re.findall(r'[\u4e00-\u9fff]{2,4}', content)
        
        # 简单频率统计
        from collections import Counter
        word_freq = Counter(words)
        
        # 过滤停用词并返回高频词
        stopwords = {'的', '是', '在', '和', '了', '有', '我', '你', '他'}
        keywords = [w for w, _ in word_freq.most_common(10) 
                   if w not in stopwords and len(w) >= 2]
        
        return keywords[:5]
    
    def _generate_suggestions(self, analysis: TitleAnalysis,
                            issues: List[str]) -> List[Dict[str, Any]]:
        """生成优化建议"""
        suggestions = []
        
        # 长度优化
        if analysis.length < self.ideal_length_min:
            suggestions.append({
                "type": "length",
                "priority": "high",
                "description": "增加标题长度",
                "detail": f"当前{analysis.length}字，建议扩充到{self.ideal_length_min}-{self.ideal_length_max}字",
                "tips": ["添加修饰词", "明确主题范围", "加入关键词"],
                "impact": 0.2
            })
        elif analysis.length > self.ideal_length_max:
            suggestions.append({
                "type": "length",
                "priority": "medium",
                "description": "精简标题",
                "detail": f"当前{analysis.length}字，建议控制在{self.ideal_length_max}字以内",
                "tips": ["删除冗余词汇", "使用简洁表达", "保留核心信息"],
                "impact": 0.15
            })
        
        # 吸引力提升
        if not analysis.has_number and not analysis.has_question:
            suggestions.append({
                "type": "attractiveness",
                "priority": "high",
                "description": "增加吸引力元素",
                "detail": "标题缺少数字或疑问词等吸引眼球的元素",
                "tips": [
                    "添加具体数字（如'5个方法'）",
                    "使用疑问句式（如'如何...'）",
                    "加入情感词汇"
                ],
                "impact": 0.25
            })
        
        # SEO优化
        if analysis.keyword_coverage < 0.5:
            suggestions.append({
                "type": "seo",
                "priority": "medium",
                "description": "提高关键词覆盖",
                "detail": "标题中关键词不足，影响搜索排名",
                "tips": [
                    "在标题前部放置主要关键词",
                    "自然融入2-3个关键词",
                    "避免关键词堆砌"
                ],
                "impact": 0.2
            })
        
        # 情感增强
        if analysis.emotional_score < 0.3:
            suggestions.append({
                "type": "emotion",
                "priority": "low",
                "description": "增强情感色彩",
                "detail": "适当的情感词汇可以提高点击率",
                "examples": self.emotion_words['positive'][:5],
                "impact": 0.1
            })
        
        return suggestions
    
    def _get_hot_keywords(self, content: str) -> List[str]:
        """获取热门关键词"""
        # 返回当前热门关键词（示例）
        # 实际应该从数据库或API获取
        current_year = datetime.now().year
        
        hot_keywords = []
        
        # 检查内容相关的热门词
        for keyword in self.hot_keywords_db:
            if content and keyword.lower() in content.lower():
                hot_keywords.append(keyword)
        
        # 如果没有找到，返回通用热门词
        if not hot_keywords:
            hot_keywords = self.hot_keywords_db[:5]
        
        return hot_keywords[:7]  # 返回最多7个
    
    def _empty_result(self, reason: str) -> TitleOptimizationResult:
        """返回空结果"""
        return TitleOptimizationResult(
            analysis=TitleAnalysis("", 0, 0, False, False, False, 0, 0, 0, []),
            attractiveness_score=0.0,
            seo_score=0.0,
            variants=[],
            issues=[reason],
            suggestions=[],
            hot_keywords=[]
        )